'use strict';
let md5 = require("./md5.js");
//
function ksort(inputArr, sort_flags) {
  var tmp_arr = {},
    keys = [],
    sorter, i, k, that = this,
    strictForIn = false,
    populateArr = {};

  switch (sort_flags) {
    case 'SORT_STRING':
      // compare items as strings
      sorter = function (a, b) {
        return that.strnatcmp(a, b);
      };
      break;
    case 'SORT_LOCALE_STRING':
      // compare items as strings, original by the current locale (set with  i18n_loc_set_default() as of PHP6)
      var loc = this.i18n_loc_get_default();
      sorter = this.php_js.i18nLocales[loc].sorting;
      break;
    case 'SORT_NUMERIC':
      // compare items numerically
      sorter = function (a, b) {
        return ((a + 0) - (b + 0));
      };
      break;
    // case 'SORT_REGULAR': // compare items normally (don't change types)
    default:
      sorter = function (a, b) {
        var aFloat = parseFloat(a),
          bFloat = parseFloat(b),
          aNumeric = aFloat + '' === a,
          bNumeric = bFloat + '' === b;
        if (aNumeric && bNumeric) {
          return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0;
        } else if (aNumeric && !bNumeric) {
          return 1;
        } else if (!aNumeric && bNumeric) {
          return -1;
        }
        return a > b ? 1 : a < b ? -1 : 0;
      };
      break;
  }

  // Make a list of key names
  for (k in inputArr) {
    if (inputArr.hasOwnProperty(k)) {
      keys.push(k);
    }
  }
  keys.sort(sorter);
  // Rebuild array with sorted key names
  for (i = 0; i < keys.length; i++) {
    k = keys[i];
    tmp_arr[k] = inputArr[k];
    if (strictForIn) {
      delete inputArr[k];
    }
  }
  for (i in tmp_arr) {
    if (tmp_arr.hasOwnProperty(i)) {
      populateArr[i] = tmp_arr[i];
    }
  }
  return strictForIn || populateArr;
}

function getSign(paramArr, key) {
  //所有参数组合完整
  let timestr = new Date().getTime();
  let headertmp = getUrlParam(timestr);
  let headerParam = getUrlParam(timestr);
  headertmp.appsecret = "029d33cff213147256c2c08daf722bd7324644e85d8bfc174c4c1e011b3ea8a7";
  // let paramtmp = Object.assign({}, headertmp, paramArr);
  // console.log("拷贝后：paramtmp="+JSON.stringify(paramtmp));

  //法二：循环
  let tempParamArr = paramArr;
  console.log("tempParamArr:" + JSON.stringify(tempParamArr))
  let paramtmp = headertmp;
  for (var i in tempParamArr) {
    if (tempParamArr.hasOwnProperty(i) == true) {
      paramtmp[i] = tempParamArr[i]
    }
  }

  //对参数进行排序
  paramtmp = ksort(paramtmp);
  //生成访问的参数 与 post参数的json，与header
  let urlString = urlPack(paramtmp);
  urlString = urlString + key;
  console.log("urlString:" + urlString)

  urlString = md5.md5(urlString);
  urlString = urlString.toUpperCase();
  console.log("---sign:" + urlString);
  return {
    sign: urlString, header: headerParam, bodyParam: paramArr
  }
}
function urlPack(arr) {
  let buff = "";
  for (let k in arr) {
    if (k != "sign" && arr[k] != "") {
      buff = buff + k + "=" + arr[k] + "&";
    }
  }
  buff = buff.replace(/(&$)/g, "");
  return buff;
}

function getUrlParam(timestr) {
  let paramJson = {
    appid: "4b0444069dc13f97a70eed8157d7ae1aed5ac6b9",
    timestamp: timestr,
    noncestr: timestr,
    method: 'POST'
  }
  // paramJson = Object.assign(paramJson, signArr);
  return paramJson;
}
function randomString() {
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = chars.length;
  var pwd = '';
  for (var i = 0; i < 32; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}
function createTimeStamp() {
  // return parseInt(new Date().getTime() / 1000) + ''
  return new Date().getTime();
}
module.exports = {
  ksort: ksort,
  getSign: getSign,
  randomString: randomString,
  createTimeStamp: createTimeStamp
}